package com.yoshino.leetcode.improve40.eighth;

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = null, cur = head, temp;
        while (cur != null) {
            temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        l1 = reverseList(l1);
        l2 = reverseList(l2);
        ListNode root = new ListNode(), head = root;
        int carry = 0, cur;
        while (l1 != null || l2 != null || carry != 0) {
            cur = carry;
            if (l1 != null) {
                cur += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                cur += l2.val;
                l2 = l2.next;
            }
            head.next = new ListNode(cur % 10);
            head = head.next;
            carry = cur / 10;
        }
        return reverseList(root.next);
    }

    public void reorderList(ListNode head) {
        if (head == null || head.next == null) {
            return;
        }
        ListNode mid = head, last = head;
        while (last.next != null && last.next.next != null) {
            mid = mid.next;
            last = last.next.next;
        }
        ListNode tmp = mid.next, temp;
        mid.next = null;
        tmp = reverseList(tmp);
        last = head;
        while (tmp != null) {
            temp = last.next;
            last.next = tmp;
            tmp = tmp.next;
            last.next.next = temp;
            last = temp;
        }
        if (last != null && last.next != null) {
            last = last.next;
        }
    }
}